Field = class("Field")

function Field.create()
    
    local field = Field.new()
    field:init()

    Field.all = Field.all or {}         --在gamescene destroy（）时会释放它，保证每次新建场景时他是新的
    Field.all[#Field.all+1] = field
    
    field.idx = #Field.all
    
    return field
end
  
function Field:init()
   self.elm = {}
   self.isEnd = false
   self.adj = {}
end

function Field:addElement(bb)
    self.elm[#self.elm+1] = bb
    bb.field = self
end

function Field:addAdjEach( field )
	-- body
    self.adj[field] = true
    field.adj[self] = true
end

--*兼并*
function Field:concat(field)
    --将field的所有元素合并进来
    for k,v in pairs(field.elm) do
        --dbg
        if IS_DEBUG then
            for m,n in pairs(self.elm) do
               if n == v then
                   assert(false, "add the same elm!")
               end
            end
        end
        
        self.elm[#self.elm+1] = v
        v.field = self      --原field所有元素的field替换成self的 !!!
    end
    
    for k in pairs(field.adj) do
        --将f的邻接信息合并到self
        self.adj[k] = true    
         
        --替换f邻接的所有field的对f的邻接信息，从f改成self     ->移到field:removeSelf()
        --k.adj[field] = nil    
                
        k.adj[self] = true    
    end
    field:removeSelf()
end
 
function Field:removeSelf()
    self:removeFromAdjs()
    local all = Field.all
    for i,v in ipairs(all) do
    	if v == self then
    		table.remove(all, i)
    	end
    end
    self = nil 
end

--清除邻接信息
function Field:removeFromAdjs()
    for k in pairs(self.adj) do
        k.adj[self] = nil
    end
end

function Field:setEnd(isEnd)
	self.isEnd = isEnd
end

function Field.dumpGraph(graph)

	for k,v in ipairs(graph) do
        for m,n in ipairs(v) do
            if n ~= 0 --[[ and n.class.__cname == "Bubble" ]]then
                d_print("field$"..n.field.idx.." ("..n.row..","..n.col.."): type == "..n.itype.." {")

                d_print("   <elm>")
                for s,q in pairs(n.field.elm)do
                    
                    d_print("       ("..q.row..","..q.col..");")
                end
                
                local a = {}
                for v in pairs(n.field.adj)do a[#a+1] = v end
                d_print("   <adj> len:"..#a)
--                a = {}
--                for v in pairs(n.field.adjEnd)do a[#a+1] = v end
--                d_print("   <adjEnd> len:"..#a)

                d_print("} \n")
            end
        end
        d_print("\n")
    end

end